import { login, logout, getInfo } from "@/api/user";
import {
  setLoginStatus,
  removeLoginStatus,
  removeJWTToken,
} from "@/utils/auth";
import { resetRouter } from "@/router";

const getDefaultState = () => {
  return {
    name: "",
    avatar: "",
    group: "",
    id: "",
    system_config: {
      k8s: {
        template_server: "http://as.hf.free4inno.com/resource",
      },
    },
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_GROUP: (state, group) => {
    state.group = group;
  },
  SET_ID: (state, id) => {
    state.id = id;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
};

// 解析后端返回的用户数据，存入VUEX，并加载动态路由
function resolveUserData(commit, response) {
  const { data } = response;
  const { groupId, name, id, system_config } = data;

  var parsed_system_config = parseSystemConfig(system_config);

  commit("SET_GROUP", groupId);
  commit("SET_NAME", name);
  commit("SET_ID", id);
  commit("SET_SYSTEM_CONFIG", parsed_system_config);

  // 生成动态路由
  GenerateRouter(parsed_system_config);
}

function parseSystemConfig(jsonString) {
  const data = JSON.parse(jsonString);

  const systemConfig = {};

  data.groups.forEach((group) => {
    const groupName = group.name;
    const groupConfig = {};

    groupConfig.available = false;

    if (group.routes) {
      group.routes.forEach((route) => {
        if (
          route.name != null &&
          route.name != "" &&
          route.uri !== null &&
          route.uri !== ""
        ) {
          groupConfig[route.name] = route.uri;
          groupConfig.available = true;
        }
      });
    }

    if (group.configs) {
      group.configs.forEach((config) => {
        if (
          config.name != null &&
          config.value != "" &&
          config.value !== null &&
          config.value !== ""
        ) {
          groupConfig[config.name] = config.value;
          groupConfig.available = true;
        }
      });
    }

    systemConfig[groupName] = groupConfig;
  });

  return systemConfig;
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, uuid, code } = userInfo;
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password,
        uuid: uuid,
        code: code,
      })
        .then((response) => {
          const { name, avatar, groupId, id } = response.data;

          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          commit("SET_GROUP", groupId);
          commit("SET_ID", id);

          setLoginStatus();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response) => {
          const { data } = response;
          if (!data) {
            return reject("Verification failed, please Login again.");
          }
          const { name, avatar, groupId, id } = data;

          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          commit("SET_GROUP", groupId);
          commit("SET_ID", id);
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          removeJWTToken();
          removeLoginStatus();
          resetRouter();
          commit("RESET_STATE");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetState({ commit }) {
    return new Promise((resolve) => {
      removeJWTToken();
      removeLoginStatus();
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
